<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class AgentCashService
{
    /**
     * 客户充值
     * @param int $cash_type (1=充值 2=扣款 3=订单消费)
     */
    public function recharge($id, $amount, $cash_type) {
        $code = 200;
        try {
            DB::beginTransaction();
            $res = DB::table('agents')->where('id', $id)->lockForUpdate()->get()->toArray();
            $balance = ((int)$res[0]->cash) / 100;
            $updated_at = $res[0]->updated_at;
            $final_balance = 0;
            switch ($cash_type) {
                case 1:
                    $final_balance = ($balance + $amount) * 100;
                    break;
                case 2:
                    if (abs($amount) > $balance) {
                        return 1003;
                    } else {
                        $final_balance = ($balance - abs($amount)) * 100;
                    }
                    break;
            }
            DB::update("update agents set cash=? where id=? && updated_at=?", [$final_balance, $id, $updated_at]);
            $conditions = [$id, $cash_type, $amount, $balance, $final_balance, time(), time()];

            DB::insert("insert into cashes(user_id, cash_type, amount, before_amount, after_amount, created_at, updated_at) values(?,?,?,?,?,?,?)", $conditions);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $code = 1001;
        }
        return $code;
    }

}
